<template>
  <div :class="['dropdown', isActive && 'is-active']" @click="toggleActive">
    <div class="dropdown-trigger">
      <slot name="trigger"></slot>
    </div>
    <div class="" :class="['dropdown-menu', placementClass, !isActive && 'is-hidden']" ref="dropdownMenu">
      <slot></slot>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'pui-dropdown',
});
</script>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue';

import type { Props } from './interface';

const props = withDefaults(defineProps<Props>(), {
  placement: 'top-end',
  disabled: false,
  popper: null,
});

const isActive = ref(false);
const placementClass = ref(`dropdown-menu--${props.placement}`);

watch(
  () => props.placement,
  () => {
    placementClass.value = `dropdown-menu--${props.placement}`;
  }
);

const handleClickOutside = (e: Event) => {
  if (!isActive.value || !props.popper) return;
  const dropdownMenu = document.querySelector('.dropdown-menu');
  const popperElement = props.popper.element || dropdownMenu;
  if (!popperElement.contains(e.target)) {
    isActive.value = false;
  }
};

const toggleActive = () => {
  if (props.disabled) return;
  isActive.value = !isActive.value;
};

onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});
</script>
